import React, {Component} from 'react';
import {Relax} from 'iflux2';
import {Map, OrderedSet, fromJS, List} from 'immutable';

import classNames from 'classnames';
import moment from 'moment';
import {orderStatus} from '../constant/order-status';
import {orderColumns} from '../constant/columns';

import {Row, Col, Checkbox, Table, Icon, Popover, Button, Popconfirm} from 'antd';
import {Link} from 'react-router';

import Deliver from '../../common/deliver';
import Refund from '../../common/refund';
import Image from 'components/Image';

import noop from 'util/noop';

import {routerShape} from 'constant/PropTypes';
import {createLocationDescriptor} from 'util/history';
import { defaultAvatorImage } from 'constant/image.js'

@Relax
export default class OrderItem extends Component {
    static defaultProps = {
        order: Map(),
        type: 'sales',
        expressCompany: List(),
        selectedRowKeys: OrderedSet(),
        userLogos: Map(),

        payAmount: 0,
        tradeOrder: Map(),
        payTypeBOList: List(),


        selectRow: noop,
        deliveryOrder: noop,
        copyTrade: noop,
        cancelOrder: noop,
        refundBefore: noop,
        refund: noop
    };

    constructor(props) {
        super(props);

        this.state = {
            open: false,
            visible: false,
            confirmLoading: false,
            refund_visible: false,
            deliver_tid: ''
        }
    }

    //路由跳转
    static contextTypes = {
        router: routerShape
    }

    

    position = () => {
        let listWidth = $('.order-goods-list:last').width();
        $('.list-ct').css({'left': parseInt(listWidth / 2)});
    }

    render() {
        const {order, selectedRowKeys, selectRow, payAmount, tradeOrder, payTypeBOList, userLogos} = this.props;
        const {open, refund_visible} = this.state;

        const openState = classNames('order-list-item-bd', {open});

        return (
            <div className="order-list-item">
                <div className="order-list-item-hd">
                    <Row>
                        <Col span={18}>
                            <Checkbox checked={selectedRowKeys.includes(order.get('tid'))} onChange={()=>{selectRow(order.get('tid'))}}/>
                            <div className="buyer-avatar"><Image width={32}
                                                                 height={32}
                                                                 auto={true}
                                                                 src={userLogos.get(order.get('buyUsercode'))
                                                                 || defaultAvatorImage}/></div>
                            <div className="order-info">
                                <p>
                                    <span className="mr10">{`买家：${order.get('buyNickName')}`}</span>
                                    <span className="mr10 t-grayer">{`收货人：${order.getIn(['consigneeInfo', 'consigneeName'])}`}</span>
                                    <span className="mr10 t-grayer">{order.getIn(['consigneeInfo', 'consigneeMobile'])
                                    || order.getIn(['consigneeInfo', 'consigneePhone'])}</span>
                                </p>
                                <p>
                                    <span className="mr10">{`订单号：${order.get('tid')}`}</span>
                                    <span className="mr10 t-grayer">{order.get('payTypeName')}</span>
                                    <span className="mr10 t-grayer">{`配送方式：${order.get('shipMethodName')}`}</span>
                                    <span className="mr10 t-grayer">{`下单时间：${moment(order.get('ctime')).format('YYYY/MM/DD HH:mm:ss')}`}</span>
                                </p>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div className="t-right">
                                <p className="order-status lh36">{orderStatus[order.get('orderStatus')]}</p>
                            </div>
                        </Col>
                    </Row>
                </div>
                <div className={openState}>
                    <Table showHeader={false}
                           pagination={false}
                           columns={this.renderColumns()}
                           dataSource={[order.toJS()]}
                        />
                    {/*
                        order.get('itemOrders').count() > 1
                            ? <a href="javascript:void(0);"><Icon className="list-ct t-grayer"
                                                                  type={open ? 'up' : 'down'} onClick={()=>this.showMore()}/></a>
                            : null
                    */}
                </div>
                <Refund tradeOrder={tradeOrder}
                        payAmount={payAmount}
                        payTypeBOList={payTypeBOList}
                        visible={refund_visible}
                        showModal={this.showRefundModal}
                        onOk={this.reimburse}/>
            </div>
        )
    }


    showRefundModal = (visible)=>{
        this.setState({
            refund_visible: visible
        })
    }

    reimburse = (params)=>{
        return this.props.refund(params);
    }


    /**
     * 列渲染
     * @returns {string|Buffer|Array.<T>|*|{options, browsertest, dist, rhino, rhinolessc}}
     */
    renderColumns() {
        const {order, expressCompany, type} = this.props;
        const {visible, confirmLoading} = this.state;
        return orderColumns(type).concat([
            {
                title: '操作',
                width: 270,
                key: 'orderOpt',
                className:"ant-table-th-right pr8 va-t",
                render: (value, record, index) => {
                    return (
                        <div className="button-list">
                            <Link to={`/order/detail/${!!type && type.toLowerCase() === 'unpay' ? 'unpay' : 'sales'}/${order.get('tid')}`}><Button type="ghost" className="pushl">看详情</Button></Link>
                            {this.renderOpts()}
                            <Deliver order={order}
                                     visible={visible}
                                     confirmLoading={confirmLoading}
                                     expressCompany={expressCompany}
                                     onOk={(values)=>this.onOk(values)}
                                     onCancel={()=>this.setState({visible: false})}/>
                        </div>
                    )
                }
            }
        ])
    }


    /**
     * 发货操作
     * @param values
     */
    onOk(values) {
        this.setState({confirmLoading: true});
        this.props.deliveryOrder(values).then(()=>{
            this.setState({
                visible: false,
                confirmLoading: false});
        }).catch(err=>{
            this.setState({
                confirmLoading: false
            });
        });
    }


    /**
     * 订单状态对于不同操作
     * @returns {[XML,XML]}
     */
    renderOpts() {
        const {order, type} = this.props;
        const orderStatus = this.props.order.get('orderStatus');
        let opts = [];

        if (orderStatus === 'WAIT_PAY') {
            opts.push([
                <Popconfirm placement="topLeft"
                            title="确定取消订单吗？"
                            onConfirm={()=>this.cancelOrder()}><Button type="ghost" className="pushl">取消</Button></Popconfirm>
                , <Link to={`/order/edit/${!!type && type.toLowerCase() === 'unpay' ? 'unpay' : 'sales'}/${order.get('tid')}`}><Button type="ghost" className="pushl">修改</Button></Link>
            ])
        } else if (orderStatus === 'WAIT_DELIVER' && order.get('deliverable')) {
            if (order.get('payTypeId') === 'GRP') {
                opts.push([
                    <Popconfirm placement="topLeft"
                                title="确定取消订单吗？"
                                onConfirm={()=>this.cancelOrder()}><Button type="ghost" className="pushl">取消</Button></Popconfirm>
                ]);
            } else {
                opts.push([
                    <Button type="ghost" className="pushl" onClick={this.refund}>申请退款</Button>
                ]);
            }
            opts.push([
                <Button type="ghost" className="pushl" onClick={()=>this.setState({visible: true})}>发货</Button>
            ])
        } else if (orderStatus === 'SUCCESS' && order.get('isApplyReturn') == 1 && order.get('applyState') == '0') {
            opts.push([
                <Link to={`/after/sales/${order.get('tid')}`}><Button type="ghost" className="pushl">代客退货</Button></Link>
            ])
        }



        return opts;
    }


    refund =()=>{
        const {refundBefore, order} = this.props;
        refundBefore(order.get('tid')).then(()=>{
            this.showRefundModal(true);
        })
    }

    /**
     * 取消订单
     */
    cancelOrder() {
        const {cancelOrder, order} = this.props;
        cancelOrder(order.get('tid'));
    }


    copyTrade = ()=>{
        const {order, copyTrade} = this.props;
        copyTrade(order).then(()=>{
            this.context.router.replace(createLocationDescriptor(`/order/start/${order.get('tid')}`));
        })
    }


    /**
     * 展示更多商品信息
     */
    showMore() {
        this.setState({
            open: !this.state.open
        })
    }
}